import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/home'
import Login from '../views/login'
import CreateMoment from '../views/createMoment'

// 解决路由守卫报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    redirect:'/home'
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    children:[
      {
        path:'/createMoment',
        name:'createMoment',
        component:CreateMoment,
        meta:{
          requiresAuth:true
        }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next)=>{
  if(to.matched.some(item=>item.meta.requiresAuth)){
    let flag = localStorage.getItem('token')
    if(flag){
      next()
    }else{
      next({
        path:'/login',
        query:{ redirect : to.fullPath }
      })
    }
  }else{
    next()
  }
})

export default router
